//
//  RHDevBatteryDataChartView.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/19.
//

#import "RHDevBatteryDataChartView.h"
#import "RHMaskView.h"
#import "DeviceChartFieldModel.h"
#import "DeviceChartItemView.h"
#import "RHLeftAxisFormatter.h"
#import "RHRightAxisFormatter.h"
#import "RHBatteryMarkerView.h"

@interface RHDevBatteryDataChartView()<ChartAxisValueFormatter>
@property (nonatomic ,copy) NSArray *colorList;
//前一天
@property (nonatomic ,strong) QMUIButton *l_btn;
//后一天
@property (nonatomic ,strong) QMUIButton *r_btn;
//日期
@property (nonatomic ,strong) QMUIButton *timeBtn;

@property (nonatomic, strong) NSMutableArray *unitLabArr;

//气泡
@property (nonatomic, strong) RHBatteryMarkerView *topMarker;

@property (nonatomic, strong) RHBatteryMarkerView *bottomMarker;
/// 图表
@property (nonatomic, strong) LineChartView *top_lineChartView;

@property (nonatomic, strong) LineChartView *bottom_lineChartView;

//年,月,日
@property (nonatomic ,assign) NSInteger type;

@property (nonatomic, assign) NSInteger selectIndex;

@property (nonatomic, strong) UIView *scrollBgView;

@property (nonatomic, strong) UIScrollView *scroll;

@property (nonatomic, strong) UIView *contentView;

@property (nonatomic, strong) NSMutableArray *itemsArray;

@property (nonatomic, strong) NSMutableArray *unitArr;

@end
@implementation RHDevBatteryDataChartView

- (instancetype)initWithFrame:(CGRect)frame type:(NSInteger)type{
    self = [super initWithFrame:frame];
    if (self) {
        self.colorList = @[@"#57BFF5",@"#98D767",@"#D177FB",@"#FDD015",@"#98D767",@"FB6085",@"8956F8"];
        self.type = type;
        [self setupUI];
        
    }
    return self;
}


- (void)setChartModel:(DevChartModel *)chartModel{
   
    _chartModel = chartModel;
    self.selectIndex = _chartModel.timeType;
    [self setChartData];
    NSString *timeStr;
    if (_chartModel.timeType == TimeType_Day) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateStyle:NSDateFormatterMediumStyle];
        [formatter setTimeStyle:NSDateFormatterShortStyle];
        [formatter setDateFormat:@"YYYY-MM-dd"];
        NSString *dateTime = [formatter stringFromDate:date];
        timeStr = dateTime;
        [_r_btn setEnabled:[date isToday]?NO:YES];
    }else if (_chartModel.timeType == TimeType_Month) {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%02ld-%02ld",[date year],[date month]];
        [_r_btn setEnabled:[[NSDate date] monthsLaterThan:date]?YES:NO];
    }else if (_chartModel.timeType == TimeType_Year){
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:[_chartModel.curTime integerValue]];
        timeStr = [NSString stringWithFormat:@"%ld",[date year]];
        [_r_btn setEnabled:[[NSDate date] yearsLaterThan:date]?YES:NO];
    }else{
        timeStr = @"";
    }

    [self.timeBtn setTitle:ValidStr(timeStr)?timeStr:@"" forState:UIControlStateNormal];
    
    __block CGFloat total_width = 0;
    kWeakSelf;
    [self.itemsArray enumerateObjectsUsingBlock:^(DeviceChartItemView  *_Nonnull itemView, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat item_width = 0;
        DeviceChartFieldModel *model;
        if (idx<self.chartModel.selectArray.count) {
            model = self.chartModel.selectArray[idx];
            model.colorStr = self.colorList[idx];
            [itemView setModel:model];
            NSAttributedString *attr = [[NSAttributedString alloc] initWithString:model.alias.rh_localized];
            CGSize size = [itemView.conentLab getLableSizeWithAttStr:attr maxHeight:15];
            item_width = size.width+25;
            [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(item_width);
            }];
            [itemView setHidden:NO];
            total_width = total_width+item_width+5;
        }else{
            [itemView setHidden:NO];
            [itemView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.mas_equalTo(0);
            }];
        }
        
        [self.scrollBgView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(MIN(self.frame.size.width,total_width+5));
        }];
    
        itemView.selectBlock = ^BOOL(DeviceChartFieldModel * _Nonnull model) {
            model.isShowLine = !model.isShowLine;
            [weakSelf.chartModel updateyAxisArray];
            [weakSelf setChartData];
            return YES;
        };
    }];

}

-(void)setChartData
{
    //更新marker数据
    DevChartModel *chartModel1 = [[DevChartModel alloc]init];
    DevChartModel *chartModel2 = [[DevChartModel alloc]init];
    
    NSMutableArray *colorArr1 = [NSMutableArray array];
    NSMutableArray *colorArr2 = [NSMutableArray array];
    
    [chartModel1.selectArray addObject:self.chartModel.selectArray[0]];
    [chartModel1.selectArray addObject:self.chartModel.selectArray[1]];
    [colorArr1 addObject:self.colorList[0]];
    [colorArr1 addObject:self.colorList[1]];
    chartModel1.xTitlesArray = self.chartModel.xTitlesArray;
    
    [chartModel2.selectArray addObject:self.chartModel.selectArray[2]];
    [chartModel2.selectArray addObject:self.chartModel.selectArray[3]];
    [colorArr2 addObject:self.colorList[2]];
    [colorArr2 addObject:self.colorList[3]];
    chartModel2.xTitlesArray = self.chartModel.xTitlesArray;

    [self.topMarker updateModel:chartModel1 colors:colorArr1];
    [self.bottomMarker updateModel:chartModel2 colors:colorArr2];
    
    
    [self.top_lineChartView clear];
    [self.bottom_lineChartView clear];
    //X轴要显示的数据
   
    NSInteger labelCount = 6;
    
    [self.top_lineChartView.xAxis setLabelCount:labelCount force:YES];//设置x轴显示的个数
  
    [self.bottom_lineChartView.xAxis setLabelCount:labelCount force:YES];//设置x轴显示的个数

    [self.unitArr removeAllObjects];
    kWeakSelf;
    __block CGFloat left_y_max = 0;
    __block CGFloat right_y_max = 0;
    NSMutableArray *dataSets_1 = [[NSMutableArray alloc] init];
    NSMutableArray *dataSets_2 = [[NSMutableArray alloc] init];

    [self.unitLabArr enumerateObjectsUsingBlock:^(QMUILabel*  _Nonnull label, NSUInteger idx, BOOL * _Nonnull stop) {
        label.text = @"";
    }];
    [self.chartModel.selectArray enumerateObjectsUsingBlock:^(DeviceChartFieldModel  *_Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        QMUILabel *unitLab = weakSelf.unitLabArr[idx];
        unitLab.text = model.unitName;
        if(model.isShowLine){
            LineChartDataSet *set = [weakSelf createDataSetWithModel:model linecolor:weakSelf.colorList[idx]];
        
            if(idx % 2 == 0){
                set.axisDependency = AxisDependencyLeft;
            }else{
                set.axisDependency = AxisDependencyRight;
            }
            
            if(idx<2){//
                [dataSets_1 addObject:set];
                if (idx == 0) {
                    weakSelf.top_lineChartView.leftAxis.axisMaximum = model.y_max;
                    weakSelf.top_lineChartView.leftAxis.axisMinimum = model.y_min;
                    
                }
                if (idx == 1) {
                    weakSelf.top_lineChartView.rightAxis.axisMaximum = model.y_max;
                    weakSelf.top_lineChartView.rightAxis.axisMinimum = model.y_min;
                    
                }

            }else{
                [dataSets_2 addObject:set];
                if (idx == 2) {
                    weakSelf.bottom_lineChartView.leftAxis.axisMaximum = model.y_max;
                    weakSelf.bottom_lineChartView.leftAxis.axisMinimum = model.y_min;
                   
                }
                if (idx == 3) {
                    weakSelf.bottom_lineChartView.rightAxis.axisMaximum = model.y_max;
                    weakSelf.bottom_lineChartView.rightAxis.axisMinimum = model.y_min;
                    
                }

            }
            
        }
        
    }];
    
    [self caculateYAxisMaxLabelWidth];
    
    //创建 LineChartData 对象, 此对象就是lineChartView需要最终数据对象
    LineChartData *lineData_1 = [[LineChartData alloc] initWithDataSets:dataSets_1];
    self.top_lineChartView.data = lineData_1;
    
    LineChartData *lineData_2 = [[LineChartData alloc] initWithDataSets:dataSets_2];
    self.bottom_lineChartView.data = lineData_2;
    //这里可以调用一个加载动画即1s出来一个绘制点
//    [self.lineChartView animateWithXAxisDuration:0.2f];
   
    //通知data去更新
    [self.top_lineChartView.data notifyDataChanged];
    [self.bottom_lineChartView.data notifyDataChanged];
    //通知图表去更新
    [self.top_lineChartView notifyDataSetChanged];
    [self.bottom_lineChartView notifyDataSetChanged];
}


/// 设置Y轴标签的宽度
-(void)caculateYAxisMaxLabelWidth
{
    //Y轴标签的宽度限制,为了曲线高亮时虚线能对齐
    NSString *top_left_max = [@(self.top_lineChartView.leftAxis.axisMaximum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat top_left_max_width = [top_left_max getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
    
    NSString *top_left_min = [@(self.top_lineChartView.leftAxis.axisMinimum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat top_left_min_width = [top_left_min getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
    
    NSString *top_right_max = [@(self.top_lineChartView.rightAxis.axisMaximum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat top_right_max_width = [top_right_max getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
    
    NSString *top_right_min = [@(self.top_lineChartView.rightAxis.axisMinimum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat top_right_min_width = [top_right_min getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
    
    
    NSString *bottom_left_max = [@(self.bottom_lineChartView.leftAxis.axisMaximum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat bottom_left_max_width = [bottom_left_max getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
    
    NSString *bottom_left_min = [@(self.bottom_lineChartView.leftAxis.axisMinimum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat bottom_left_min_width = [bottom_left_min getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
    
    NSString *bottom_right_max = [@(self.bottom_lineChartView.rightAxis.axisMaximum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat bottom_right_max_width = [bottom_right_max getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
    
    NSString *bottom_right_min = [@(self.bottom_lineChartView.rightAxis.axisMinimum) decimalPlacesWithRoundUpWithDigit:2];
    CGFloat bottom_right_min_width = [bottom_right_min getStringWidthFont:kSYSTEMFONT(12) limitHeight:20];
  
    
    NSArray *valueArr = @[@(top_left_max_width),@(top_left_min_width),@(top_right_max_width),@(top_right_min_width),@(bottom_left_max_width),@(bottom_left_min_width),@(bottom_right_max_width),@(bottom_right_min_width)];
    CGFloat result_width = [[valueArr valueForKeyPath:@"@max.floatValue"] floatValue]+3;
    
    self.top_lineChartView.leftAxis.maxWidth = result_width;
    self.top_lineChartView.leftAxis.minWidth = result_width;
    self.top_lineChartView.rightAxis.maxWidth = result_width;
    self.top_lineChartView.rightAxis.minWidth = result_width;
    
    self.bottom_lineChartView.leftAxis.maxWidth = result_width;
    self.bottom_lineChartView.leftAxis.minWidth = result_width;
    self.bottom_lineChartView.rightAxis.maxWidth = result_width;
    self.bottom_lineChartView.rightAxis.minWidth = result_width;
}



#pragma mark ----- 创建曲线
-(LineChartDataSet*)createDataSetWithModel:(DeviceChartFieldModel*)model linecolor:(NSString*)colorStr;
{
    NSMutableArray *entryArr = [[NSMutableArray alloc]init];
    
    [self.chartModel.xTitlesArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ChartDataEntry *entry = [[ChartDataEntry alloc] initWithX:idx y:[model.dataArray[idx] floatValue]];
        [entryArr addObject:entry];
    }];
    
    LineChartDataSet *set = [[LineChartDataSet alloc] initWithEntries:entryArr label:model.keyName];
    [set setColor:kCOLOR_HEX(colorStr)];//折线颜色
    //set1.lineDashLengths = @[@4.0,@2.0];//设置虚线各段长度
    set.mode = LineChartModeHorizontalBezier;//曲线平滑显示   贝塞尔曲线
    //数据太多的时候不使用平滑显示,会卡
    if(model.dataArray.count>500){
        set.mode = LineChartModeLinear;
    }
    set.drawIconsEnabled = YES;//是否绘制图标
    set.formLineWidth = 1.1;//图例的线宽
    set.formSize = 8.0;//图例的字体大小
    set.lineWidth = 2.0;//折线的宽度
    

    set.drawCirclesEnabled = NO;//是否绘制拐点
    set.drawCircleHoleEnabled = YES;//是否画空心圆
    set.circleColors = @[kCOLOR_HEX(colorStr)];//外圆颜色
    set.circleHoleColor = UIColor.whiteColor; //内圆颜色
    set.circleRadius = 2; //外圆半径
    set.circleHoleRadius = 1; //内圆半径
    
    set.drawValuesEnabled = NO;//是否在拐点处显示数据
    set.valueColors = @[kCOLOR_HEX(colorStr)];//拐点上的文字颜色
    set.valueFont = [UIFont systemFontOfSize:8];//拐点上的文字大小
    
    //折线拐点样式
    //第二种填充样式:渐变填充
    set.drawFilledEnabled = YES;//是否填充颜色
    NSArray *gradientColors = @[(id)[UIColor colorWithHexString:colorStr alpha:0.15].CGColor,
                                (id)[UIColor colorWithHexString:colorStr alpha:0.0].CGColor];
    CGGradientRef gradientRef = CGGradientCreateWithColors(nil, (CFArrayRef)gradientColors, nil);
    set.fillAlpha = 1.0f;//透明度
    set.fill = [[ChartLinearGradientFill alloc]initWithGradient:gradientRef angle:-90.0f];//赋值填充颜色对象
    CGGradientRelease(gradientRef);//释放gradientRef
    
    //点击选中拐点的交互样式
    set.highlightEnabled = YES;//选中拐点,是否开启高亮效果(显示十字线)
    set.drawVerticalHighlightIndicatorEnabled = YES; //不显示纵向十字线
    set.drawHorizontalHighlightIndicatorEnabled = NO; //不显示横向十字线
    set.highlightColor = kRGB(23,23,23);//点击选中拐点的十字线的颜色
    set.highlightLineWidth = 1.1/[UIScreen mainScreen].scale;//十字线宽度
    set.highlightLineDashLengths = @[@5, @5];//十字线的虚线样式
    
    return set;
}

- (void)setupUI{
    [self setBackgroundColor:UIColor.whiteColor];
    UIView *itemBgView = [[UIView alloc] init];
    [itemBgView setBackgroundColor:UIColor.whiteColor];
    [self addSubview:itemBgView];
    itemBgView.hidden = YES;
    kWeakSelf;
    UIView *line = kView;
    line.backgroundColor = CMainColorGreen;
    [self addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
            make.height.offset(2);
    }];
    line.hidden = YES;
    
    NSArray *titles = @[@"日".rh_localized,@"月".rh_localized,@"年".rh_localized];
    if (self.type == 0) {
        titles = @[@"日".rh_localized,@"月".rh_localized,@"年".rh_localized];
    }else if (self.type == 1){
        titles = @[@"日".rh_localized,@"月".rh_localized];
    }else if (self.type == 2){
        titles = @[@"日".rh_localized];
    }
    __block QMUIButton *lastbtn;
   
    [titles enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        //    NSAttributedString *attr = [[NSAttributedString alloc] initWithString:_nameStr];
        //CGSize size = [self.nameLab getLableSizeWithAttStr:attr maxHeight:18];
        QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
        [btn setBackgroundColor:UIColor.whiteColor];
        [btn setTitle:obj forState:UIControlStateNormal];
        [btn setTitleColor:FontColor(@"#000000") forState:UIControlStateNormal];
        [btn.titleLabel setFont:[UIFont systemFontOfSize:13]];
        btn.layer.cornerRadius = 10;
        btn.layer.masksToBounds = YES;
        CGFloat width = [obj getStringWidthFont:btn.titleLabel.font limitHeight:200];
        [itemBgView addSubview:btn];
        
        if(idx == 0){
            [line mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(btn.mas_bottom).offset(0);
                    make.centerX.equalTo(btn);
                    make.width.equalTo(btn).offset(-10);
            }];
        }
        
        [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [weakSelf btnAction:idx];
            [line mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(x.mas_bottom).offset(0);
                    make.centerX.equalTo(x);
                    make.width.equalTo(x).offset(-10);
                    make.height.offset(2);
            }];
            
        }];
        
        
        [RACObserve(weakSelf, selectIndex) subscribeNext:^(id  _Nullable x) {
            NSInteger index = [x integerValue];
            NSLog(@"--->index:%ld  button:%@",index,btn);
            if (index == idx) {
                [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:12]];
                [btn setTitleColor:kCOLOR_HEX(@"323233") forState:UIControlStateNormal];
                btn.backgroundColor = [UIColor colorWithHexString:@"5DD8AB" alpha:0.25];
            }else{
                [btn.titleLabel setFont:[UIFont systemFontOfSize:12]];
                [btn setTitleColor:kCOLOR_HEX(@"969799") forState:UIControlStateNormal];
                btn.backgroundColor = UIColor.whiteColor;
            }
            
        }];
        
        if (!lastbtn) {
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(0.5);
                make.top.mas_offset(0.5);
                make.bottom.mas_offset(-0.5);
                make.width.mas_equalTo(width+20);
                make.height.offset(25);
            }];
        }else{
            [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastbtn.mas_right).offset(2);
                make.top.mas_offset(0.5);
                make.bottom.mas_offset(-0.5);
                make.width.mas_equalTo(width+20);
                make.height.offset(25);
            }];
        }
        lastbtn = btn;
    }];
    
    [lastbtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(-0.5);
    }];
    
    [itemBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_offset(20);
    }];
    
    //全屏
    QMUIButton *full_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [full_btn setImagePosition:QMUIButtonImagePositionRight];
    [full_btn setImage:[UIImage imageNamed:@"full_screen"] forState:UIControlStateNormal];
    [full_btn setTitle:@"" forState:UIControlStateNormal];
    [self addSubview:full_btn];
    full_btn.hidden = YES;
    
    //时间
    QMUIButton *dateBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [dateBtn setBackgroundColor:UIColor.whiteColor];
    [dateBtn setTitle:@"2023-08-09" forState:UIControlStateNormal];
    [dateBtn setImagePosition:QMUIButtonImagePositionRight];
    dateBtn.spacingBetweenImageAndTitle = 5;
    [dateBtn setTitleColor:FontColor(@"#000000") forState:UIControlStateNormal];
    [dateBtn.titleLabel setFont:[UIFont systemFontOfSize:12]];
    [self addSubview:dateBtn];
    self.timeBtn = dateBtn;
    
    //上一天
    _l_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_l_btn setImagePosition:QMUIButtonImagePositionRight];
    [_l_btn setImage:[UIImage imageNamed:@"day_left"] forState:UIControlStateNormal];
    [self addSubview:_l_btn];
    
    //下一天
    _r_btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [_r_btn setImagePosition:QMUIButtonImagePositionRight];
    [_r_btn setImage:[UIImage imageNamed:@"day_right"] forState:UIControlStateNormal];
    [self addSubview:_r_btn];

    _top_lineChartView = [self createLineChartView];
    _top_lineChartView.xAxis.drawLabelsEnabled = NO;//不绘制X轴时间
    [self addSubview:self.top_lineChartView];
    _bottom_lineChartView = [self createLineChartView];
    [self addSubview:self.bottom_lineChartView];
    
    self.topMarker = [[RHBatteryMarkerView alloc]init];
    self.top_lineChartView.marker = self.topMarker;
    self.topMarker.chartView = self.top_lineChartView;
    
    self.bottomMarker = [[RHBatteryMarkerView alloc]init];
    self.bottom_lineChartView.marker = self.bottomMarker;
    self.bottomMarker.chartView = self.bottom_lineChartView;
    
    //添加单位
    QMUILabel *leftUnitLab = [[QMUILabel alloc]init];
    leftUnitLab.textColor = UIColor.lightGrayColor;
    leftUnitLab.font = [UIFont systemFontOfSize:13];
    [self addSubview:leftUnitLab];
    [self.unitLabArr addObject:leftUnitLab];
    
    QMUILabel *rightUnitLab = [[QMUILabel alloc]init];
    rightUnitLab.textColor = UIColor.lightGrayColor;
    rightUnitLab.font = [UIFont systemFontOfSize:13];
    [self addSubview:rightUnitLab];
    [self.unitLabArr addObject:rightUnitLab];
    
    QMUILabel *leftUnitLab_b = [[QMUILabel alloc]init];
    leftUnitLab_b.textColor = UIColor.lightGrayColor;
    leftUnitLab_b.font = [UIFont systemFontOfSize:13];
    [self addSubview:leftUnitLab_b];
    [self.unitLabArr addObject:leftUnitLab_b];
    
    QMUILabel *rightUnitLab_b = [[QMUILabel alloc]init];
    rightUnitLab_b.textColor = UIColor.lightGrayColor;
    rightUnitLab_b.font = [UIFont systemFontOfSize:13];
    [self addSubview:rightUnitLab_b];
    [self.unitLabArr addObject:rightUnitLab_b];
    
    [leftUnitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.top_lineChartView).offset(5);
        make.top.equalTo(dateBtn.mas_bottom).offset(0);
    }];
    
    [rightUnitLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.top_lineChartView).offset(-5);
        make.centerY.equalTo(leftUnitLab);
    }];
    
    
    
    [full_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 40));
        make.right.mas_offset(-5);
        make.centerY.equalTo(lastbtn);
    }];
    
    
    
    [dateBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(full_btn.mas_top).offset(5);
        make.size.mas_equalTo(CGSizeMake(80, 30));
        make.centerX.mas_offset(0);
    }];
    
    [_l_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.right.equalTo(dateBtn.mas_left);
    }];

    [_r_btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(50, 30));
        make.centerY.equalTo(dateBtn);
        make.left.equalTo(dateBtn.mas_right);
    }];
    
    [self.top_lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(leftUnitLab.mas_bottom).offset(5);
        make.height.offset(kScaleW(200));
    }];
    
    [leftUnitLab_b mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftUnitLab);
        make.top.equalTo(weakSelf.top_lineChartView.mas_bottom).offset(10);
    }];
    
    [rightUnitLab_b mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(rightUnitLab);
        make.centerY.equalTo(leftUnitLab_b);
    }];
    
    [self.bottom_lineChartView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.top.equalTo(leftUnitLab_b.mas_bottom).offset(5);
        make.height.offset(kScaleW(200));
    }];
   
    //下面的曲线标签按钮
    _scrollBgView = [[UIView alloc] init];
    [_scrollBgView setBackgroundColor:UIColor.orangeColor];
    [self addSubview:_scrollBgView];
    
    _scroll = [[UIScrollView alloc] init];
    [_scroll setShowsHorizontalScrollIndicator:NO];
    _scroll.backgroundColor = [UIColor whiteColor];
    [_scrollBgView addSubview:_scroll];
    
    _contentView = [[UIView alloc] init];
    _contentView.backgroundColor = [UIColor whiteColor];
    [_scroll addSubview:_contentView];
    
    __block DeviceChartItemView *lastItem;
    __block CGFloat width = 5;
    [self.colorList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        DeviceChartItemView *itemView = [[DeviceChartItemView alloc] init];
        [itemView.markLab.layer setBorderColor:FontColor(obj).CGColor];
//        [itemView shadow:UIColor.blackColor opacity:0.1 radius:5 offset:CGSizeMake(0, 1)];
        [_contentView addSubview:itemView];
        [self.itemsArray addObject:itemView];

        if (!lastItem) {
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_offset(width);
                make.top.mas_offset(5);
                make.centerY.mas_offset(0);
                make.height.mas_equalTo(20);
                make.width.mas_equalTo(0);
            }];
            width = width;
        }else{
            [itemView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(lastItem.mas_right).offset(5);
                make.top.mas_offset(5);
                make.centerY.mas_offset(0);
                make.height.mas_equalTo(20);
                make.width.mas_equalTo(0);
            }];
            width = width+5;
        }
        lastItem = itemView;
    }];
    
    [lastItem mas_updateConstraints:^(MASConstraintMaker *make) {
        make.right.mas_offset(0);
    }];
    
    
    [self.scrollBgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_offset(0);
        make.top.equalTo(self.bottom_lineChartView.mas_bottom).offset(0);
        make.bottom.mas_offset(-10);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(MIN(self.frame.size.width,width));
    }];
    
    
    [_scroll mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];
    
    [_contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
        make.width.greaterThanOrEqualTo(@0.f);//此处保证容器View高度的动态变化 大于等于0.f的高度
    }];
    
    
    [[full_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf fullAction];
    }];
    
    [[_l_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {//日期往前
        if (weakSelf.subTimeBlock) {
            weakSelf.subTimeBlock();
        }
    }];
    
    [[_r_btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {//日期往后
        if (weakSelf.addTimeBlock) {
            weakSelf.addTimeBlock();
        }
    }];
    
    [[dateBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (weakSelf.changeTimeBlock) {
            weakSelf.changeTimeBlock();
        }
    }];
}


- (void)fullAction{
    if (self.fullChartBlock) {
        self.fullChartBlock();
    }
}

- (void)btnAction:(NSInteger)index{
    if (self.selectTopToolBlock) {
        self.selectTopToolBlock(index);
    }
    
    if (index == -1) {//自定义参数设置
        return;
    }
    
    self.selectIndex = index;
    NSLog(@"---->选择的下标:%d",index);
    if (self.selectIndex == 1) {//Day
        
    }
    
    if (self.selectIndex == 2) {//Month
        
    }
    
    if (self.selectIndex == 3) {//Year
        
    }
    
    if (self.selectIndex == 4) {//Total
        
    }
}



- (LineChartView *)createLineChartView{
  
    LineChartView *lineChartView = [[LineChartView alloc]init];
    lineChartView.delegate = self;
       
    lineChartView.chartDescription.enabled = NO;  //是否显示描述label
    lineChartView.extraRightOffset = 0;//右边缩进
    lineChartView.extraLeftOffset = 0;
    lineChartView.extraBottomOffset = 0;//图表底部缩进,也就是与图例的距离
    lineChartView.backgroundColor = kRGB(255, 255, 255);

    lineChartView.noDataText = @"没有数据".rh_localized;//没有数据时显示的文字
       
    lineChartView.legend.enabled = NO;//是否显示说明图标
    lineChartView.legend.form = ChartLegendFormSquare;//说明图例的样式
    lineChartView.legend.formSize = 3;//图例大小（头部）
    lineChartView.legend.formToTextSpace = 5;//图例与文字的距离
    lineChartView.legend.yOffset = 10;//图例与底部的距离
    lineChartView.legend.xEntrySpace = 20;//图例与图例之间的距离
    lineChartView.legend.neededHeight = 50;
    lineChartView.legend.stackSpace = 10;
    lineChartView.dragEnabled = YES; //拖动手势
    lineChartView.highlightPerDragEnabled = NO;//高亮拖拽
    lineChartView.dragDecelerationEnabled = YES;//拖拽后是否有惯性效果
    lineChartView.dragDecelerationFrictionCoef = 0.9;//拖拽后惯性效果的摩擦系数(0~1)，数值越小，惯性越不明显
    lineChartView.pinchZoomEnabled = YES; //捏合手势
    lineChartView.doubleTapToZoomEnabled = NO;  //禁止双击缩放
    lineChartView.drawGridBackgroundEnabled = NO; //绘制图形区域背景
    lineChartView.drawBordersEnabled = NO; //绘制图形区域边框
    lineChartView.scaleYEnabled = NO;//Y轴不允许缩放
    lineChartView.scaleXEnabled = NO;//Y轴不允许缩放
    lineChartView.rightAxis.enabled = YES;  //隐藏右Y轴
    //    [self.LineChartView setVisibleXRangeMaximum:5];// 最大显示区域
    //    [self.LineChartView setVisibleXRangeMinimum:1];// 最小显示区域
    //气泡标签
    lineChartView.drawMarkers = YES;
        
//    ChartMarkerView *marker = [[ChartMarkerView alloc]
//                                 init];
//    marker.offset = CGPointZero;
//    marker.chartView = lineChartView;
////        marker.minimumSize = CGSizeMake(60.f, 20.f);
////        marker.image = [UIImage imageNamed:@""];
//        
//    RHMaskView *maskView = [[RHMaskView alloc] initWithFrame:CGRectMake(0, 0, 100, 44)];
//    [marker addSubview:maskView];
//    self.maskView = maskView;
    
    
    
        //只滑动不缩放
    //    ChartViewPortHandler *scalX = self.LineChartView.viewPortHandler;
    //    [scalX setMinimumScaleX:1.01];
        
        
    //设置左Y轴
    ChartYAxis *leftAxis =lineChartView.leftAxis;
    leftAxis.labelPosition = YAxisLabelPositionOutsideChart;//label位置
    leftAxis.axisLineWidth = 1;
    leftAxis.axisMaxLabels = 6;     //y轴展示多少个
    [leftAxis setLabelCount:6 force:YES];
    leftAxis.labelFont = [UIFont systemFontOfSize:12];
    leftAxis.labelTextColor = UIColor.lightGrayColor; //文本颜色
    leftAxis.axisLineColor = kRGB(217, 217, 217);    //左Y轴线条颜色
//    leftAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
    leftAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:0.8];//网格线颜色
    leftAxis.gridAntialiasEnabled = YES;//开启抗锯齿
    leftAxis.zeroLineColor = [UIColor redColor];    //左Y轴底线条颜色
    leftAxis.drawZeroLineEnabled = NO;//绘制0线
    leftAxis.valueFormatter = self;
    leftAxis.axisMinimum = 0;//Y轴最小值
//        leftAxis.axisMaximum = 150;   //Y轴最大值
    leftAxis.drawAxisLineEnabled = NO;//Y轴线

    
    //设置 右-->Y轴
    ChartYAxis *rightAxis = lineChartView.rightAxis;
    rightAxis.labelPosition = YAxisLabelPositionOutsideChart;//label位置
    rightAxis.axisLineWidth = 1;
    rightAxis.axisMaxLabels = 6;     //y轴展示多少个
    [rightAxis setLabelCount:6 force:YES];
    rightAxis.labelFont = [UIFont systemFontOfSize:12];
    rightAxis.labelTextColor = UIColor.lightGrayColor; //文本颜色
    rightAxis.axisLineColor = kRGB(217, 217, 217);    //左Y轴线条颜色
//    rightAxis.gridLineDashLengths = @[@3.0f, @3.0f];//设置虚线样式的网格线
    rightAxis.gridColor = [UIColor colorWithRed:200/255.0f green:200/255.0f blue:200/255.0f alpha:0.8];//网格线颜色
    rightAxis.gridAntialiasEnabled = YES;//开启抗锯齿
    rightAxis.zeroLineColor = [UIColor redColor];    //左Y轴底线条颜色
    rightAxis.drawZeroLineEnabled = NO;//绘制0线
    rightAxis.valueFormatter = self;
    rightAxis.axisMinimum = 0;//Y轴最小值
//        rightAxis.axisMaximum = 150;   //Y轴最大值
    rightAxis.drawAxisLineEnabled = NO;//Y轴线
    
    
    // 设置X轴
    ChartXAxis *xAxis = lineChartView.xAxis;
    xAxis.axisLineWidth = 1.0/[UIScreen mainScreen].scale;//设置X轴线宽
    xAxis.axisLineColor = UIColor.lightGrayColor;
    xAxis.labelPosition =XAxisLabelPositionBottom; //x轴文字的位置
    xAxis.labelFont = [UIFont systemFontOfSize:12];//文字字体
    xAxis.labelTextColor = UIColor.lightGrayColor;//文字颜色
//    xAxis.labelCount = 5;
    xAxis.axisMaxLabels = 6;//x轴最多显示个数;
    xAxis.axisMinLabels = 2;//x轴最少显示个数;
    xAxis.granularity = 1;//x轴标题中间最小的间隔

    xAxis.drawGridLinesEnabled = NO;//是否画网格
    xAxis.gridColor = UIColor.redColor;//x轴对应网格线的颜色
    xAxis.gridLineWidth = 1;//x轴对应网格线的大小
    xAxis.gridLineDashLengths = @[@4,@2];  //虚线各段长度
//    xAxis.labelRotationAngle = -30.0;//设置文字旋转角度
    

    //自定义数据显示格式
//     NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
//    [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
//    [formatter setPositiveFormat:@"#0.0"];
//    formatter.positivePrefix = @"#";
//    xAxis.valueFormatter = [[ChartDefaultAxisValueFormatter alloc]initWithFormatter:formatter];
    xAxis.valueFormatter = self;

    
    
    //加载动画时长
//    [lineChartView animateWithYAxisDuration:0.2 easingOption:ChartEasingOptionEaseInBack];
    
    return lineChartView;
}

#pragma mark --------------------chartView delegate ------------------
 - (NSString *)stringForValue:(double)value axis:(ChartAxisBase *)axis
 {
     //x轴
     if ([axis isEqual:self.top_lineChartView.xAxis]||[axis isEqual:self.bottom_lineChartView.xAxis]) {
         NSInteger index = (NSInteger)value;
         return [self.chartModel.xTitlesArray safeObjectAtIndex:index];
     }

     //y轴
     NSNumber *number =  [NSNumber numberWithDouble:value];
     NSString *numberString = [number decimalPlacesWithRoundUpWithDigit:2];
     return  [NSDecimalNumber decimalStringWithDouble:[numberString doubleValue]];
 }
#pragma mark 图表中数值被选中
-(void)chartValueSelected:(ChartViewBase *)chartView entry:(ChartDataEntry *)entry highlight:(ChartHighlight *)highlight{

 
    if ([chartView isEqual:self.top_lineChartView]) {
        [self.bottom_lineChartView highlightValue:highlight];
    }
    
    if ([chartView isEqual:self.bottom_lineChartView]) {
        [self.top_lineChartView highlightValue:highlight];
    }
      
}

#pragma mark 图表中的空白区域被选中
-(void)chartValueNothingSelected:(ChartViewBase *)chartView{
    NSLog(@"空白区域被选中");
    if([chartView isEqual:self.top_lineChartView]){
        [self.bottom_lineChartView highlightValues:@[]];
    }else{
        [self.top_lineChartView highlightValues:@[]];
    }
    
}

#pragma mark 图表被缩放
-(void)chartScaled:(ChartViewBase *)chartView scaleX:(CGFloat)scaleX scaleY:(CGFloat)scaleY{
//    NSLog(@"图表被缩放");
    //根据缩放调整显示间隔
//    if(scaleX>=3){
//        self.lineChartView.xAxis.granularity = 1;
//    }else if(scaleX>=2){
//        self.lineChartView.xAxis.granularity = 2;
//    }
//    chartView.xAxis.granularity = self.chartModel.xTitlesArray.count/8*scaleX;
    NSLog(@"------>图表缩放倍数:%f",scaleX);
 
     CGAffineTransform srcMatrix = chartView.viewPortHandler.touchMatrix;

     [self.bottom_lineChartView.viewPortHandler refreshWithNewMatrix:srcMatrix chart:self.bottom_lineChartView invalidate:YES];

     [self.top_lineChartView.viewPortHandler refreshWithNewMatrix:srcMatrix chart:self.top_lineChartView invalidate:YES];

    
}

#pragma mark 图表被移动
-(void)chartTranslated:(ChartViewBase *)chartView dX:(CGFloat)dX dY:(CGFloat)dY{
//    NSLog(@"图表被移动");
    CGAffineTransform srcMatrix = chartView.viewPortHandler.touchMatrix;

    [self.bottom_lineChartView.viewPortHandler refreshWithNewMatrix:srcMatrix chart:self.bottom_lineChartView invalidate:YES];

    [self.top_lineChartView.viewPortHandler refreshWithNewMatrix:srcMatrix chart:self.top_lineChartView invalidate:YES];

}



#pragma mark ------ lazy load

- (NSMutableArray *)itemsArray{
    if (!_itemsArray) {
        _itemsArray = [NSMutableArray array];
    }
    return _itemsArray;
}

-(NSMutableArray *)unitArr
{
    if(!_unitArr)
    {
        _unitArr = [NSMutableArray array];
    }
    return _unitArr;
}
-(NSMutableArray *)unitLabArr
{
    if(!_unitLabArr)
    {
        _unitLabArr = [NSMutableArray array];
    }
    return _unitLabArr;
}
@end
